package cn.itcast.loginfilter;

import cn.itcast.pojo.Common;
import cn.itcast.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

//@Component
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
//    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化过滤器");
    }

    /**
     * 执行过滤器逻辑，对请求进行预处理和后处理
     *
     * @param servletRequest  Servlet请求对象，包含客户端请求信息
     * @param servletResponse Servlet响应对象，用于向客户端发送响应
     * @param filterChain     过滤器链，用于调用下一个过滤器或目标资源
     * @throws IOException      当发生输入输出异常时抛出
     * @throws ServletException 当发生Servlet相关异常时抛出
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取uri
        String uri = request.getRequestURI();
        if (uri.contains("/login") || uri.contains("/register")) {
            filterChain.doFilter(servletRequest, servletResponse);

            return;
        }
        //判断是否有令牌
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(401);

            return;
        }

        try {
            Claims claims = tokenUtil.parseToken(token);

            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            //令牌可能被篡改或者已经失效
            response.setStatus(401);
        } finally {
            Common.threadLocal.remove();
        }
    }

}
